package io.feige.rpc.spring;

import io.feige.rpc.producer.RpcProducerService;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

@SuppressWarnings("rawtypes")
public class ServiceBean implements InitializingBean, DisposableBean, ApplicationContextAware, ApplicationListener, BeanNameAware {
 
	//private static final Logger logger=LoggerFactory.getLogger(ServiceBean.class);
	
	private static RpcProducerService rpcProducerService;
	
	private String interfaceName;
	
	private String ref;

	private ApplicationContext applicationContext;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		if (rpcProducerService==null) {
			rpcProducerService=new RpcProducerService();
			rpcProducerService.start();
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext=applicationContext;
	}
 

    public void setInterfaceName(String interfaceName) { 
        this.interfaceName = interfaceName;
    }
  
	@Override
	public void destroy() throws Exception {
		rpcProducerService.stop();
	}

	@Override
	public void setBeanName(String name) {

 	}

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		try {
			rpcProducerService.exportService(Class.forName(interfaceName), applicationContext.getBean(ref));
		} catch (Exception e) {
			throw new IllegalArgumentException(e);
		} 
		
	}

	public String getRef() {
		return ref;
	}

	public void setRef(String ref) {
		this.ref = ref;
	}

}